#ifdef MSVC
	#include "SDL_image.h"
    #include "SDL_ttf.h"
#else
	#include "SDL/SDL_image.h"
    #include "SDL/SDL_ttf.h"
#endif

#include "constants.h"
#include "logger.h"
#include <sstream>

SDL_Surface* transparent_sprite( SDL_Surface * sprite )
{
    Uint32 colorkey = SDL_MapRGB( sprite->format, 0, 0, 0 );
    SDL_SetColorKey( sprite, SDL_SRCCOLORKEY, colorkey );
    return sprite;
}

SDL_Surface *load_image( const char * filename )
{
    SDL_Surface* loadedImage = NULL;
    SDL_Surface* optimizedImage = NULL;
    loadedImage = IMG_Load( filename );
    if( loadedImage != NULL )
    {
        optimizedImage = SDL_DisplayFormat( loadedImage );
        SDL_FreeSurface( loadedImage );
        optimizedImage = transparent_sprite(optimizedImage);
    }
    else
    {
        // TODO: else throw exception
        log_error(string("Couldn't load image: ") + filename);
    }
    return optimizedImage;
}

/*
 * Това слага нещо върху нещо друго. Информативна документация, йей.
 * */
void apply_surface(int x, int y, SDL_Surface* source, SDL_Surface* destination, SDL_Rect* clip = NULL)
{
    SDL_Rect offset;
    offset.x = x;
    offset.y = y;
    SDL_BlitSurface( source, clip, destination, &offset );
}

SDL_Surface* CreateSurface(int width,int height, SDL_Surface * display)
{
  const SDL_PixelFormat& fmt = *(display->format);
  return SDL_CreateRGBSurface(0,width,height,
                  fmt.BitsPerPixel,
                  fmt.Rmask,fmt.Gmask,fmt.Bmask,fmt.Amask );
}

// Променливи използвани за печатане на екрана.
SDL_Surface *screen_message = NULL;
TTF_Font *font = NULL;
SDL_Color text_color = { 255, 255, 0 };

bool set_font(const char * filename)
{
    font = TTF_OpenFont( "fonts/DooM.ttf", 28 );
    return font != NULL;
}

// Това е екранът от главния файл на играта.
extern SDL_Surface * screen;

/*
 * Изписва съобщение в центъра на екрана.
 * */
bool display_message(const char * message, int x, int y)
{
    screen_message = TTF_RenderText_Solid( font, message, text_color );
    if(screen_message == NULL)
    {
        log_error("Unable to display text");
        return false;
    }
    apply_surface(
        x-screen_message->w/2,
        y,
        screen_message,
        screen
    );
    SDL_FreeSurface(screen_message);
    return true;
}

/*
 * Изписва информация на екрана (Например, "Press Enter to continue")
 * */
bool display_info(const char * message)
{
    return display_message(message, SCREEN_WIDTH/2, SCREEN_HEIGHT/2 + TILE_SIZE*3);
}

bool display_score(int score)
{
    stringstream the_score;
    the_score<<score;
    
    return display_message(the_score.str().c_str(), 24*TILE_SIZE, 34*TILE_SIZE);
}
